<?php

include("../UserIncludes/DbConfig.php");
$mdid=$_REQUEST['advertiseid'];

// $mdid='093f65e080a295f8076b1c5722a46aa2';
// $mdid='32bb90e8976aab5298d5da10fe66f21d';
// $mdid='d2ddea18f00665ce8623e36bd4e3c7c5';
// $mdid='c4ca4238a0b923820dcc509a6f75849b'; // 1
if($mdid=='')$mdid='c4ca4238a0b923820dcc509a6f75849b'; // For debug


$path_offset="/sio-cms/";
$path="http://".$_SERVER['HTTP_HOST'];
$path=$path.$path_offset;

//$SQL="SELECT AP.`adspaceId`, AP.`adsiteId`, `AS`.`ctr_grade` FROM `adsite_master` `AS`,`adspace_master` AP WHERE `AS`.`adsiteId`=AP.`adsiteId` AND AP.`adspaceIdMd`='".$mdid."' AND AP.`status`='Y'";
$SQL_main="SELECT AP.`adspaceId`, AP.`adsiteId`, `AS`.`ctr_grade`, AD.* FROM `adsite_master` `AS`,`adspace_master` AP, `adspace_details` AD WHERE AD.`adspaceId`=AP.`adspaceId` AND `AS`.`adsiteId`=AP.`adsiteId` AND AP.`adspaceIdMd`='".$mdid."' AND AP.`status`='Y'";

//echo $SQL_main."<br>";
$RS_main=mysql_query($SQL_main) or die("Error #val");
if(mysql_num_rows($RS_main)){
$ROW_main=mysql_fetch_array($RS_main) or die("Error #val2");
$sp=$ROW_main['adspaceId'];  // adspace id
$ctr_grade=$ROW_main[ctr_grade];  // Site's CTR grade (A,B,C,D,E)
#######################################



    $cellSpacing = 6;
    $cellPadding = 6;
    $rows = 1;
    $cols = 1;
    $sizes =explode("x", $ROW[adSize]);
    $totalWidth = $sizes[0];
    $totalHeight = $sizes[1];

    switch ($ROW_main[adSize]) {
        case "184x360" :
            $adsno = 5;
            $rows = 5;
            $descriptionFontSize = "12px";
            break;
        case "468x60" :
            $adsno = 2;
            $cellSpacing = 6;
            $alignment = "horizontal";
            $cols = 2;
            $titleFontSize = "12px";
            $descriptionFontSize = "11px";
            break;
        case "234x60" :
            $adsno = 1;
            $cellSpacing = 6;
            $titleFontSize = "12px";
            $descriptionFontSize = "12px";
            break;
        case "728x90" :
            $adsno = 5;
            $alignment = "horizontal";
            $cols = 5;
            $descriptionFontSize = "12px";
            break;
        case "125x125" :
            $adsno = 1;
            $cellSpacing = 0;
            $titleFontSize = "12px";
            $descriptionFontSize = "12px";
            break;
        case "120x240" :
            $adsno = 3;
            $rows = 3;
            $titleFontSize = "12px";
            $descriptionFontSize = "12px";
            break;
        case "180x150" :
            $adsno = 1;
            $titleFontSize = "12px";
            $descriptionFontSize = "12px";
            break;
        case "300x250" :
            $adsno = 4;
            $cols = 2;
            $rows = 2;
            break;
        case "336x280" :
            $adsno = 6;
            $cols = 3;
            $rows = 2;
            break;
        case "250x250" :
            $adsno = 4;
            $cols = 2;
            $rows = 2;
            break;
        case "120x600" :
            $adsno = 6;
            $rows = 6;
            break;
        case "160x600" :
            $adsno = 7;
            $rows = 7;
            break;
        default :
            $adsno =$ROW_main[noOfTextAd];
            $cellSpacing = 6;
            $alignment =strtolower($ROW_main[thumbOrientation]);
            if($alignment=='horizontal')$cols =$adsno;
            else $rows = $adsno;
            $width = $sizes[0];
            $height = $sizes[1];
            $totalWidth =$width*$cols;
            $totalHeight = $height*$rows;
            break;
    }
   //echo "Cols: ".$cols." Rows: ".$rows." Adsno: ".$adsno."<br>";
    
    if($ROW_main[fontType]!=""){
    $fontType=$ROW_main[fontType];
    }else{
    $fontType="Arial";
    }
    if($ROW_main[backgroundColor]!=""){
    $backgroundColor=$ROW_main[backgroundColor];
    }else{
    $backgroundColor="#E8E8E8";
    }
    //echo $backgroundColor;
    if($ROW_main[headerColor]!=""){
    $headerColor=$ROW_main[headerColor];
    }else{
    $headerColor="#E8E8E8";
    }
    //echo $headerColor;
    if($ROW_main[bodyColor]!=""){
    $bodyColor=$ROW_main[bodyColor];
    }else{
    $bodyColor="#000000";
    }
$c=0;
$r=0;

####################################
}else die("Blocked");
# First check the adsite has been passed the filter or not --- `site_approval_map`, `approval_filter`

$nets=array(); // Store network ids to which the publisher site belongs to
$ads=array();
$slots=array(6,12,18,24); // Define the time slots for the campaign ads to run evenly throughout the day
$country=IP2Country($_SERVER['REMOTE_ADDR']);  // Necessary to run the ads limited for a particular geographic locations
# Fetch country id from DB
$SQL="SELECT countryId FROM `country` WHERE countries_iso_code_2='".$country."'";
$RS=mysql_query($SQL) or die();
if(mysql_num_rows($RS)){
$ROW=mysql_fetch_array($RS);
$countryId=$ROW[countryId];
}


$SQL="";
/*$SQL.=" SELECT AD.*,SD.*,AM.* FROM advertise_details AD, adspace_details SD,advertise_master AM";
$SQL.=" WHERE AD.adspaceId=SD.adspaceId AND AD.advertiseId=AM.advertiseId AND SD.adspaceIdMd='".$mdid."' ";
$SQL.=" AND AM.startDate <= CURDATE() AND AM.endDate >= CURDATE()";
$SQL.=" AND AM.advertiseStatus = 'Y' ";
$SQL.=" AND AD.networkId = 0 ";
*/
$SQL="SELECT SD.*,AM.* FROM adspace_details SD,adspace_master AM 
		WHERE AM.adspaceId=SD.adspaceId 
		AND AM.status = 'Y' 
		AND AM.readyDate >= CURDATE() 
		AND AM.adspaceIdMd='".$mdid."' ";
		$RS=mysql_query($SQL) or die("Error !! #2=>".mysql_error()."<br>".$SQL);
		$ctr=0;
		$RS=mysql_query($SQL) or die(mysql_error()." ".$SQL);
		
		# Inser into track for every visit
		$SQLimp="INSERT INTO `advertise_impression_trac` (adsiteId,adspaceId,campaign_ad,adgroup_ad_id,adgroup_id,campaign_id,client_IP,country,visit_time)VALUES";
		$i=0;
		while($ROW=mysql_fetch_array($RS))
		{
			$SQLimp.="(".$sites[0].",".$sp.",'Y',".$ROW[adgroup_ad_id].",".$ROW[adgroup_id].",".$ROW[campaign_id].",'".$_SERVER['REMOTE_ADDR']."','".$country."',NOW()),";
			$i++;
			//print_r($ROW);
			## Check whether to Run throughout the day 
			if($ROW[spend_memo]=='all_day')
			{
				$flag=0;
				foreach($slots as $k=>$v)
				{
					if(date("H")<=$v && $ROW[today_spent]>=(($k+1)*$ROW[daily_budget])/count($slots)) 
					{
						$flag=1;
						break;
					}	
				}
				reset($slots); // Reset the poiter of the array 
				if($flag)continue;
			}
			## Determine the current campaign ad is whether target to custom network or predefined network
			if($ROW[network_type]=='direct')$N='D';
			else if($ROW[network_type]=='custom')$N='C';
			////////////////////////////////////////////////////
			//echo "<pre>";
			//var_dump($ROW);
			//echo "</pre>";
			if($ROW[description]=="")
			{
				$ROW[description]="No description avail..";
				$htmlstart='<table width="'.$totalWidth.'" height="'.$totalHeight.'" border="0" cellspacing="'.$cellSpacing.'"><tr>';
				$htmlend='</table>';
				if($c<=$cols)
				{
					$html.='<td><table width="'.$width.'" height="'.$height.'" border="0" cellspacing="'.$cellSpacing.'" cellpadding="6" bgcolor="'.$backgroundColor.'">
					<tr><td align="center"><a href="'.$path.'wbk/?a='.__randit().$ROW[adgroup_ad_id].__randit().'&g='.__randit().$ROW[adgroup_id].__randit().'&c='.__randit().$ROW[campaign_id].__randit().'&s='.__randit().$sites[0].__randit().'&val='.$mdid.'&N='.$N.'" style="text-decoration:none;"><font color="'.$headerColor.'" style="font-family: '.$fontType.';">'.$ROW[heading].'</font><br><br><font color="'.$bodyColor.'" style="font-family: '.$fontType.';">'.$ROW[description].'</font></a></td></tr>
					</table></td>';
					$c++;
				}
				if($c==$cols)
				{
					$html.='</tr><tr>';
					$r++;
					$c=0;
				}
				if($r==$rows)
				{
					$ads[]=htmlentities($htmlstart.$html.$htmlend);
					$html="";
					$r=0;
				}
			}
			else
			{
				
				$htmlstart='<table width="'.$totalWidth.'" height="'.$totalHeight.'" border="0" cellspacing="'.$cellSpacing.'"><tr>';
				$htmlend='</table>';
				if($c<=$cols)
				{
					$html.='<td>
							<table width="'.$width.'" height="'.$height.'" border="0" cellspacing="'.$cellSpacing.'" cellpadding="6" bgcolor="'.$backgroundColor.'">
								<tr>
									<td align="center">
										<a href="'.$path.'wbk/?a='.__randit().$ROW[adgroup_ad_id].__randit().'&g='.__randit().$ROW[adgroup_id].__randit().'&c='.__randit().$ROW[campaign_id].__randit().'&s='.__randit().$sites[0].__randit().'&val='.$mdid.'&N='.$N.'" style="text-decoration:none;">
											<font color="'.$headerColor.'" style="font-family: '.$fontType.';">'.$ROW['adSpaceName'].'</font><br>
										</a>
										<a href="'.$path.'wbk/?a='.__randit().$ROW[adgroup_ad_id].__randit().'&g='.__randit().$ROW[adgroup_id].__randit().'&c='.__randit().$ROW[campaign_id].__randit().'&s='.__randit().$sites[0].__randit().'&val='.$mdid.'&N='.$N.'" style="text-decoration:none;">
											<img src='.$path."upload_adspace_image_thumb/".$ROW['adSpace_image'].' border="0"><br>
											</a>
										<font color="'.$bodyColor.'" style="font-family: '.$fontType.';">'.$ROW['description'].'</font>
										</td>
									</tr>
					</table></td>';
					$c++;
				}
				if($c==$cols)
				{
					$html.='</tr><tr>';
					$r++;
					$c=0;
				}
				if($r==$rows)
				{
					$ads[]=htmlentities($htmlstart.$html.$htmlend);
					$html="";
					$r=0;
				}
			}
		}






function __randit()
{
$chars = "1023456789";
    srand((double)microtime()*1000000);
    $i = 0;
    $ret = '' ;
	//generates 4 random numbers
    while ($i < 4) {
        $num = rand(1, 9);
        $tmp = substr($chars,$num,1);
        $ret = $ret . $tmp;
        $i++;
    }
return $ret;
}

function IP2Country($ipAddr)
{
$location = $ipAddr;
$q = 'http://api.local.yahoo.com/MapsService/V1/geocode?appid=rlerdorf&location='.rawurlencode($location);
$resp=file_get_contents($q);
$xml = simplexml_load_string($resp);
return $xml->Result[0]->Country;
}
//$ads=array('test','<table><tr><td>Abdul</td></tr></table>',2,3,4,5,6,7,8,9);
if(isset($_POST['Submit']) && $_POST['Submit']!= '')
{
    
   // echo $_POST['Submit'].'<br>';
    $ads=explode('@_@',$_POST['ads']);
    $counter=$_POST['counter'];
    $counter++;
   
    if($_POST['counter'] + (int)1 >= count($ads))
    {
        $counter=0;
    }
    //echo $counter;
    $ad=$ads[$counter];
}
else
{
    $counter=0;
    $ad=$ads[$counter];
}


?>

<form name="frm_ads" id="frm_ads" method="post" action="">
  <input type="hidden" name="counter" id="counter" value="<?php echo $counter;?>">
  <input type="hidden" name="ads" id="ads" value="<?php echo htmlentities(implode('@_@',$ads));?>">
  <input type="hidden" name="Submit" id="Submit" value="Submit">
</form>

<div>
    <?php echo html_entity_decode($ad); ?>
</div>

<script>
//setTimeout("SUBMITfunction();",500);
function SUBMITfunction()
{
    document.getElementById("frm_ads").submit();
}
</script>